<template>
  <div class="users-page">
    <div class="page-header">
      <h1>用户列表</h1>
    </div>
    
    <div class="content-card">
      <!-- 批量操作按钮 -->
      <div class="batch-actions">
        <el-button 
          type="danger" 
          icon="el-icon-warning"
          @click="handleBatchToggleDisable"
          :disabled="selectedUsers.length === 0"
        >
          批量禁/反禁用
        </el-button>
      </div>

      <!-- 用户表格 -->
      <el-table 
        :data="userList" 
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="index" label="序号" width="80">
          <template slot-scope="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="account" label="账号" width="120"></el-table-column>
        <el-table-column prop="account" label="姓名" width="120">
          <template slot-scope="scope">
            {{ scope.row.account }}
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="80"></el-table-column>
        <el-table-column prop="integral" label="积分" width="100"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="regtime" label="注册时间" width="120"></el-table-column>
        <el-table-column prop="disable" label="禁用状态" width="100">
          <template slot-scope="scope">
            <div 
              class="status-capsule" 
              :class="scope.row.disable === 1 ? 'disabled' : 'enabled'"
              @click="toggleUserStatus(scope.row)"
            >
              {{ scope.row.disable === 1 ? '已禁用' : '正常' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button 
              type="primary" 
              size="mini" 
              @click="showUserDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 用户详情弹框 -->
    <el-dialog
      title="用户详情"
      :visible.sync="detailDialogVisible"
      width="500px"
    >
      <div class="user-detail" v-if="selectedUser">
        <div class="detail-item">
          <span class="label">用户ID：</span>
          <span class="value">{{ selectedUser.id }}</span>
        </div>
        <div class="detail-item">
          <span class="label">账号：</span>
          <span class="value">{{ selectedUser.account }}</span>
        </div>
        <div class="detail-item">
          <span class="label">姓名：</span>
          <span class="value">{{ selectedUser.account }}</span>
        </div>
        <div class="detail-item">
          <span class="label">性别：</span>
          <span class="value">{{ selectedUser.sex }}</span>
        </div>
        <div class="detail-item">
          <span class="label">积分：</span>
          <span class="value">{{ selectedUser.integral }}</span>
        </div>
        <div class="detail-item">
          <span class="label">邮箱：</span>
          <span class="value">{{ selectedUser.email }}</span>
        </div>
        <div class="detail-item">
          <span class="label">注册时间：</span>
          <span class="value">{{ selectedUser.regtime }}</span>
        </div>
        <div class="detail-item">
          <span class="label">禁用状态：</span>
          <span class="value">
            <div 
              class="status-capsule" 
              :class="selectedUser.disable === 1 ? 'disabled' : 'enabled'"
              @click="toggleUserStatus(selectedUser)"
            >
              {{ selectedUser.disable === 1 ? '已禁用' : '正常' }}
            </div>
          </span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'   //引入axios

export default {
  name: 'UsersList',   //组件名
  data() {             //数据
    return {
      userList: [],
      selectedUsers: [],
      loading: false,
      currentPage: 1,
      pageSize: 5,
      total: 0,
      detailDialogVisible: false,
      selectedUser: null
    }
  },
  mounted() {       //生命周期的函数 ：组件创建完成后执行
    this.fetchUserList()
  },
  methods: {     //方法    
  // // 获取用户列表
    async fetchUserList() {
      this.loading = true
      try { 
        const params = new URLSearchParams()
        params.append('pageNum', Number(this.currentPage) || 1)
        params.append('pageSize', Number(this.pageSize) || 10)
        const response = await axios.post('/api/user/pageList', params, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
        
        if (response.data.code === 200) {
          this.userList = response.data.data.list
          this.total = response.data.data.total
        } else {
          this.$message.error(response.data.msg || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$message.error('获取用户列表失败')
      } finally {
        this.loading = false
      }
    },

    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedUsers = selection
    },

    // 批量禁用/反禁用
    async handleBatchToggleDisable() {
      if (this.selectedUsers.length === 0) {
        this.$message.warning('请先选择要操作的用户')
        return
      }

      // 检查选中的用户是否都是相同状态
      const allDisabled = this.selectedUsers.every(user => user.disable === 1)
      const allEnabled = this.selectedUsers.every(user => user.disable === 0)
      
      if (!allDisabled && !allEnabled) {
        this.$message.warning('请选择状态相同的用户进行批量操作')
        return
      }
    
      
      try {
        // 循环调用单个用户更新接口
        const updatePromises = this.selectedUsers.map(user => {
          const params = new URLSearchParams()
          params.append('id', user.id)
          
          return axios.post('/api/user/updateDisable', params, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          })
        })
        
        await Promise.all(updatePromises)
        
        this.$message.success('批量操作成功')
        this.fetchUserList()
        this.selectedUsers = []
      } catch (error) {
        console.error('批量操作失败:', error)
        this.$message.error('批量操作失败')
      }
    },

    // 显示用户详情
    showUserDetail(user) {
      this.selectedUser = user
      this.detailDialogVisible = true
    },

    // 切换用户禁用状态
    async toggleUserStatus(user) {
      try {
        const newDisableStatus = user.disable === 1 ? 0 : 1
        console.log('用户ID:', user.id, '新状态:', newDisableStatus);
        
        // 使用 URLSearchParams 发送 form-urlencoded 数据
        const params = new URLSearchParams()
        params.append('id', user.id)
        
        const response = await axios.post('/api/user/updateDisable', params, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        })
        
        if (response.data.code === 200) {
          this.$message.success('状态修改成功')
          // 更新本地数据
          user.disable = newDisableStatus
        } else {
          this.$message.error(response.data.msg || '状态修改失败')
        }
      } catch (error) {
        console.error('状态修改失败:', error)
        this.$message.error('状态修改失败')
      }
    },

    // 处理页码变化
    handleCurrentChange(page) {
      this.currentPage = Number(page)
      this.fetchUserList()
    },

    // 处理每页显示数量变化
    handleSizeChange(size) {
      this.pageSize = Number(size)
      this.currentPage = 1
      this.fetchUserList()
    }
  }
}
</script>

<style scoped>
.users-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  color: #333;
  font-size: 24px;
  margin: 0;
}

.content-card {
  background: white;
  border-radius: 10px;
  padding: 30px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.batch-actions {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.user-detail {
  padding: 10px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}

.detail-item .label {
  font-weight: bold;
  width: 100px;
  color: #666;
}

.detail-item .value {
  flex: 1;
  color: #333;
}

.dialog-footer {
  text-align: right;
}

.status-capsule {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  min-width: 60px;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.status-capsule.enabled {
  background-color: #3b82f6;
  color: white;
  border: 1px solid #3b82f6;
}

.status-capsule.disabled {
  background-color: #9ca3af;
  color: white;
  border: 1px solid #9ca3af;
}

.status-capsule.enabled:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}

.status-capsule.disabled:hover {
  background-color: #6b7280;
  border-color: #6b7280;
}

.status-capsule:active {
  transform: scale(0.95);
}
</style>
